package com.snatch.snatchmgr.core;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.snatch.snatchmgr.constant.SYSConstant;
import com.snatch.snatchmgr.entity.db.ThirdMatch;
import com.snatch.snatchmgr.entity.db.ThirdPlayinfo;
import com.snatch.snatchmgr.entity.db.ThirdTradingItem;
import com.snatch.snatchmgr.system.SystemData;


/**
 * 清理内存中已经过期的赔率数据信息
 */
@Component
public class ClearDataDaemon extends Thread {

	/**
	 * 清除任务间隔时间
	 */
	private long clearWaitTime = 60L * 1000;

	// 日志对象
	private Logger log = Logger.getLogger(ClearDataDaemon.class);

	private Object obj = new Object();

	@Override
	public void run() {

		while (true) {
			synchronized (obj) {
				try {
					obj.wait(clearWaitTime);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			try {
				// 清除第三数据
				log.info("开始清理第三方滚球数据");
				clearThirdData(SystemData.gqThirdDatas);
				log.info("开始清理第三方死盘数据");
				clearThirdData(SystemData.spThirdDatas);

			} catch (Exception e) {
				log.error("清除过期数据出错", e);
			}
		}
	}

	/**
	 * 清除第三方数据
	 * 
	 * @param thirdData
	 */
	private void clearThirdData(Map<String, ConcurrentHashMap<String, ThirdMatch>> thirdData) {
		for (ConcurrentHashMap<String, ThirdMatch> tlMap : thirdData.values()) {
				// 第一步做赛事清除
				Iterator<ThirdMatch> iterThirdMatch = tlMap.values().iterator();
				while (iterThirdMatch.hasNext()) {
					ThirdMatch tm = iterThirdMatch.next();
					// 在清除赛事时第一步做玩法清除
					// 清除指定时间没有更新赔率的玩法，默认10秒
					Iterator<ThirdPlayinfo> iterPlayinfo = tm.getThirdPlayinfos().values().iterator();
					while (iterPlayinfo.hasNext()) {
						ThirdPlayinfo tpi = iterPlayinfo.next();
						if ((tpi.getSystemUpdateTime() + SystemData.systemConfig.getPlayTimeOut()) < System.currentTimeMillis()) {
							iterPlayinfo.remove();
								log.info("第三方数据清除长时间没有更新赔率的玩法：" + tm.getMatchType()  +" "+ tm.getMatchName()+ "[" + tm.getTarget() + "]  => " + tpi.getName() + "[" + tpi.getGametime()
										+ "]");
							continue;
						}
					}

					// 清除长时间没有更新过的赛事
					if ((tm.getSystemUpdateTime() + SystemData.systemConfig.getMatchTimeOut()) < System.currentTimeMillis()) {
						iterThirdMatch.remove();
						log.info("移除长时间没有更新过的第三方滚球赛事：" + tm.getMatchType()  +" " + tm.getMatchName() + "[" + tm.getTarget() + "]");
						continue;
					}
				}

		}
	}



}
